#include "movieorderwidget.h"

#include <KLocale>
#include <KIcon>
#include <KPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QListWidgetItem>
#include <QVariant>
#include <QLabel>

MovieOrderWidget::MovieOrderWidget( QWidget *aParent ) : QWidget( aParent ), pMovie( NULL ), pNewMovie( NULL )
{
	QVBoxLayout *mainLayout = new QVBoxLayout( this );
	mainLayout->addWidget( new QLabel( i18n("Movie list:") ) );
	QHBoxLayout *hLayout = new QHBoxLayout( this );
	pView = new KListWidget;
	hLayout->addWidget( pView );
	mainLayout->addLayout( hLayout );
	KPushButton *btn = new KPushButton;
	btn->setIcon( KIcon("go-up") );
	btn->setText( i18n("Up") );
	connect( btn, SIGNAL( clicked() ), this, SLOT( up() ) );
	QVBoxLayout *vLayout = new QVBoxLayout;
	vLayout->addWidget( btn );
	btn = new KPushButton;
	btn->setIcon( KIcon("go-down") );
	btn->setText( i18n("Down") );
	connect( btn, SIGNAL( clicked() ), this, SLOT( down() ) );
	vLayout->addWidget( btn );
	vLayout->addStretch();
	hLayout->addLayout( vLayout );
}

MovieOrderWidget::~MovieOrderWidget()
{

}

void MovieOrderWidget::setMovie( KDCMovie *aMovie )
{
	pMovie = aMovie;
	load();
}

void MovieOrderWidget::save()
{
	if ( !pMovie )
		return;
	QList<KDCMovie*> movies = pMovie->subMovies();
	int i;
	for ( i=0; i<movies.size(); ++i )
		pMovie->removeSubMovie( i );
	movies.append( pMovie );
	pNewMovie = movies.at( pView->item( 0 )->data( Qt::EditRole ).toInt() );
	for ( i=1; i<pView->count(); ++i )
		pNewMovie->addSubMovie( movies.at( pView->item( i )->data( Qt::EditRole ).toInt() ) );
}

void MovieOrderWidget::load()
{
	if ( !pMovie )
		return;
	pView->clear();
	QListWidgetItem *item;
	for ( int i=0; i<pMovie->subMovies().size(); ++i )
	{
		item = new QListWidgetItem( pView );
		item->setText( pMovie->subMovies().at( i )->metaData()->name() );
		item->setData( Qt::EditRole, i );
		item->setCheckState( Qt::Checked );
	}
	item = new QListWidgetItem;
	item->setData( Qt::EditRole, pView->count() );
	item->setCheckState( Qt::Checked );
	item->setText( pMovie->metaData()->name() );
	pView->insertItem( 0, item );
}

void MovieOrderWidget::up()
{
	QListWidgetItem *item = pView->currentItem();
	int row = pView->currentRow();
	if ( !item || row < 1 )
		return;
	pView->takeItem( row );
	pView->insertItem( row - 1, item );
}

void MovieOrderWidget::down()
{
	QListWidgetItem *item = pView->currentItem();
	int row = pView->currentRow();
	if ( !item || row > pView->count() - 2 )
		return;
	pView->takeItem( row );
	pView->insertItem( row + 1, item );
}

KDCMovie* MovieOrderWidget::newMovie() const
{
	return pNewMovie;
}

